package com.sdp.khy.baotou.controller;

import java.time.LocalDateTime;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

import com.sdp.core.bizc.db.Query;
import com.sdp.core.bizc.utils.UniqueCheckTools;
import com.sdp.core.bizc.vo.DataCenter;
import com.sdp.core.bizc.vo.Result;
import com.sdp.khy.baotou.cache.clean.KhyCleanCache;
import com.sdp.khy.baotou.db.khy_param_info.entity.KhyParamInfo;
import com.sdp.khy.baotou.db.khy_param_info.service.IKhyParamInfoService;


@RestController
@RequestMapping("/KhyParamInfoController")
public class KhyParamInfoController {

	@Autowired
	private Query query;
	
	@Autowired
	private IKhyParamInfoService paramInfoService;
	
	@Autowired
	private UniqueCheckTools uniqueCheckTools;
	
	@Autowired
	private KhyCleanCache khyCleanCache;
	
	@PostMapping(value = "/page")
	public Result<?> page(@RequestBody DataCenter dataCenter) {
		return Result.ok(query.page(paramInfoService, KhyParamInfo.class, dataCenter));
	}
	
	@PostMapping(value = "/save")
	@Transactional(rollbackFor=Exception.class)
	public Result<?> save(@RequestBody KhyParamInfo paramInfo){
		if(paramInfo==null) {
			return Result.error("信息为空");
		}
		if(StringUtils.isEmpty(paramInfo.getKeyId())) {
			//账号不能重复和工号不能重复
			Result<?> r = uniqueCheckTools.isUniqueSingle(paramInfoService, KhyParamInfo.class, new String[] {"paramCode"}, "keyId", paramInfo, null, false);
			if(r==null || !r.isSuccess()) {
				return Result.error("参数编号重复");
			}
			paramInfo.setCreateTime(LocalDateTime.now());
			paramInfoService.save(paramInfo);
		}else {
			Result<?> r = uniqueCheckTools.isUniqueSingle(paramInfoService, KhyParamInfo.class, new String[] {"paramCode"}, "keyId", null, paramInfo, false);
			if(r==null || !r.isSuccess()) {
				return Result.error("参数编号重复");
			}
			paramInfoService.updateById(paramInfo);
		}
		khyCleanCache.cleanParamCache();
		return Result.ok(paramInfo);
	}
	
	@GetMapping(value = "/del")
	@Transactional(rollbackFor=Exception.class)
	public Result<?> del(@RequestParam(name="keyId",required=true) String keyId) {
		if(StringUtils.isEmpty(keyId)) {
			return Result.error("需要删除的记录信息不完整");
		}
		paramInfoService.removeById(keyId);
		khyCleanCache.cleanParamCache();
		return Result.ok();
	}
	
}
